package com.jintian.smart.kernel.switching.admin.service;
import com.jintian.smart.kernel.common.util.StringUtil;
import com.jintian.smart.kernel.switching.entity.TableDMLWatch;
import com.jintian.smart.kernel.switching.mapper.ITableDMLWatchMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SwitchingAdminService {
    @Autowired
    private ITableDMLWatchMapper dmlWatchMapper;

    public boolean rebuildTrigger(String tableName) {
        TableDMLWatch watch = dmlWatchMapper.single(tableName);
        this.rebuildTrigger(watch);
        return true;
    }

    public boolean rebuildTriggerAll() {
        List<TableDMLWatch> watchs = dmlWatchMapper.all();
        for (TableDMLWatch watch : watchs) {
            this.rebuildTrigger(watch);
        }
        return true;
    }

    private void rebuildTrigger(TableDMLWatch watch) {
        if (StringUtil.isBlank(watch.getOperation())) {
            watch.setOperation(TableDMLWatch.OPERATION_UPSERT + "," + TableDMLWatch.OPERATION_DELETE);
        }
        dmlWatchMapper.createTableDMLLogTrigger(watch);
    }
}
